package com.playball.lottery.fragment.frm;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.adapter.BarberGalleryAdapter;
import com.playball.lottery.adapter.KaiJiangAdapter;
import com.playball.lottery.bean.APPOfAdvertisingBean;
import com.playball.lottery.bean.KaiJiangBean;
import com.playball.lottery.customview.BarberGallery;
import com.playball.lottery.nt.animal.O2OServiceImpl;
import com.playball.lottery.nt.orjdd.JsonUtil;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.LotConstants;
import com.playball.lottery.util.OKHttpConstants;
import com.playball.lottery.util.PreferencesUtils;
import com.playball.lottery.util.province.GlobalUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.playball.lottery.util.AbstractActivity.context;


public class Tab1Fragment extends Fragment  implements LotConstants,View.OnClickListener{
    public static final String TAG = "Tab1Fragment";
    private BarberGallery headerGallery;
    private PreferencesUtils pUtil;
    private View _RootView;
    private LinearLayout indicatorLL;
    private int positon;
    private TextView top_title_back,top_title_info;
    public O2OServiceImpl o2OService;

    private LinearLayout line_goBuy;
    private TextView tv_more;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pUtil = new PreferencesUtils(getActivity(), Constants.PREFERENCES_NAME);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        _RootView = inflater.inflate(R.layout.fragment_tab1, null);

        return _RootView;
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
//		lunbo.pauseLunbo();
        super.onDestroyView();

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        o2OService=new O2OServiceImpl();
        initTitle();  //初始化标题
        initView(); //初始化控件
        getAdvertisingData();
    }
    //初始化标题
    private void initTitle(){
        top_title_back=(TextView) _RootView.findViewById(R.id.top_title_back);
        top_title_back.setVisibility(View.GONE);
        top_title_info=(TextView) _RootView.findViewById(R.id.top_title_info);
        top_title_info.setText("彩票店");
    }
    //初始化控件
    private void initView(){
        //广告位
        headerGallery = (BarberGallery) _RootView.findViewById(R.id.headerGallery);
        //点击查看更多
        tv_more=(TextView) _RootView.findViewById(R.id.tv_more);
        tv_more.setOnClickListener(this);
        //前往购买大厅
        line_goBuy=(LinearLayout) _RootView.findViewById(R.id.line_goBuy);
        line_goBuy.setOnClickListener(this);
    }
    //广告位
    private void initActivity(final List<APPOfAdvertisingBean> list) {

        if (list == null || list.size() == 0) {
            return;
        }

        headerGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                changePointView(position % list.size());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
//        headerGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
////                AppRecommendJobInfo recommendJobInfo = (AppRecommendJobInfo) parent.getItemAtPosition(position);
////                if (recommendJobInfo.type != null && recommendJobInfo.type.size() >= 2) {
////                    IntentUtils.entryWorkerDetail(context, recommendJobInfo.type.get(0).value, recommendJobInfo.type.get(1).value);
////                }
//            }
//        });
        indicatorLL = (LinearLayout) _RootView.findViewById(R.id.indicatorLLId);
        indicatorLL.removeAllViews();
        float density = GlobalUtils.getDensity(getActivity());
        for (int i = 0; i < list.size(); i++) {
            ImageView pointView = new ImageView(getActivity());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins((int) density * 10, 0, 0, 0);
            pointView.setLayoutParams(layoutParams);
            if (i == 0) {
                pointView.setBackgroundResource(R.drawable.indicator_point_pressed);
            } else
                pointView.setBackgroundResource(R.drawable.indicator_point_normal);
            indicatorLL.addView(pointView);
        }
        BarberGalleryAdapter adapter = new BarberGalleryAdapter(getActivity(), list, headerGallery);
        headerGallery.setAdapter(adapter);
    }



    /**
     * point选择切换
     *
     * @param cur
     */
    private void changePointView(int cur) {
        View view = indicatorLL.getChildAt(positon);
        View curView = indicatorLL.getChildAt(cur);
        if (view != null && curView != null) {
            ImageView pointView = (ImageView) view;
            ImageView curPointView = (ImageView) curView;
            pointView.setBackgroundResource(R.drawable.indicator_point_normal);
            curPointView.setBackgroundResource(R.drawable.indicator_point_pressed);
            positon = cur;
        }
    }

    /**
     * 点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //点击查看更多
            case R.id.tv_more:
                break;
            //前往购买大厅
            case R.id.line_goBuy:
                break;
            default:
                break;
        }
    }
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(OKHttpConstants.CONNECT_TIMEOUT, TimeUnit.SECONDS)
            .build();

    Call post(String url, String json, Callback callback) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);
        return call;
    }



   /**
     * 获取广告位数据
     */

    public  void  getAdvertisingData(){
        final ArrayList<APPOfAdvertisingBean> list=new ArrayList<APPOfAdvertisingBean>();

//        String url = o2OService.getURLOfAdvertising2();
        String url="http://mobile.tcaio2o.com/MobileHandler.ashx?platformVersion=6.0&UserID=ODMw&platformCode=Android&sign=6AC3583C15FEB7B931172E8E6AF71937&appVersion=1.0&cmdName=app_zz&uuid=3C075461B9B0&action=23&params={\"LSID\":\"3\"}";
        post(url, "", new Callback() {
            @Override
            public void onFailure (Call call, IOException e){
                e.printStackTrace();
            }

            @Override
            public void onResponse (Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseStr = response.body().string();
                    String str = responseStr.replaceAll("<a>\\s*|\t|\r|\n</a>", "").trim();
                    // Do what you want to do with the response.
//                    System.out.println(responseStr);
                    if (str != null) {
                        try {
                            JSONTokener jsonParser = new JSONTokener(str);
                            JSONObject js = (JSONObject) jsonParser.nextValue();
                            List<Map<String, Object>> Data = com.playball.lottery.util.ConvertJsonToList.getList(js.getString("Data"));
                            if (Data != null) {
                                for (int i = 0; i < Data.size(); i++) {
                                    APPOfAdvertisingBean bean = new APPOfAdvertisingBean();
                                    bean.setTitle(Data.get(i).get("Title").toString());
                                    bean.setLinkUrl(Data.get(i).get("LinkUrl").toString());
                                    bean.setImgPath(Data.get(i).get("ImgPath").toString());
                                    bean.setCreateTime(Data.get(i).get("CreateTime").toString());
                                    bean.setTypeID(Data.get(i).get("TypeID").toString());
                                    list.add(bean);
                                }

                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (list != null) {
                                           initActivity(list);

                                        }
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    // Request not successful
                    throw new IOException("Unexpected code " + response);
                }
            }
        });
        }


}
